package com.oig.sys.oauth.service;

import cn.hutool.core.date.DateUtil;
import com.oig.auth.api.PermissionService;
import com.oig.auth.api.UserService;
import com.oig.sys.auth.vo.PermissionVo;
import com.oig.sys.auth.vo.UserVo;
import com.oig.sys.security.support.SecurityUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
@RequiredArgsConstructor
public class AuthUserDetailsService implements UserDetailsService {

    private final UserService userService;
    private final PermissionService permissionService;


    @Override
    public UserDetails loadUserByUsername(String username)  {
        log.info("loadUserByUsername:{}",username);
        UserVo user = userService.loadUserByUsername(username) ;
        if (user == null) {
            log.warn("用户{}不存在", username);
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        if (user.getPwdFailNum()!=null && user.getPwdFailTime()!=null){    //密码错误次数过多 锁定账户
            if (user.getPwdFailNum()>5 && DateUtil.offsetHour(user.getPwdFailTime(),3).isAfter(new Date())){
                throw new LockedException("密码错误过多锁定账户3小时");
            }
        }
        return this.buildUser(user);
    }


    private UserDetails buildUser(UserVo user){
        List<GrantedAuthority> authorityList = new ArrayList<>();
        List<PermissionVo> permissionVoList = permissionService.loadPermissionByUserId(user.getId()) ;

        // 声明用户授权
        if (!CollectionUtils.isEmpty(permissionVoList)) {
            for (PermissionVo permission : permissionVoList) {
                if (permission != null && permission.getApiUrl() != null) {
                    authorityList.add(new SimpleGrantedAuthority(permission.getApiUrl()));
                }
            }
        }

        return new SecurityUser(user.getId(),user.getCode(),user.getNickName(),user.getRealName(), user.getUsername(), user.getPassword(),
                user.getDefaultSysId(), user.getDefaultSysName(), user.getDefaultSysImgUrl(),
                user.getTenantId(),user.getTenantCode(),user.getTenantName(),authorityList);

    }


}
